//
//  HomePage.m
//  HappyStore
//
//  Created by 点点充 on 16/1/13.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "HomePage.h"
#import "hotIndustryView.h"
#import "projectLibraryVC.h"
#import "industryClassificationVC.h"
#import "SearchProject.h"
#import "SearchProjectInfoVC.h"
#import "searchContactsVC.h"
#import "mainFabu.h"
#import "TrickTender.h"
#import "TrickTender.h"
#import "PageButtonsCell.h"

#import "LSBecomeVIPVC.h"
#import "LSRechargeVC.h"
#import "ForgetPassWord.h"
#import "LSPayResultVC.h"

#import "LSWebPages.h"
#import "LSPageWebVC.h"

#import "addFriendVC.h"

#import "detailProfile.h"
#define ITEM_SPACING 280

#define NORMAL_HEIGHT 129

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件

@interface HomePage ()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UIAlertViewDelegate>
{
    XTLoopScrollView *loopScrollView1;
    XTLoopScrollView *loopScrollView2;
    
    XTLoopScrollView *loopScrollViewMain;
    
    NSDictionary *dicWeather1;
    
    NSDictionary *dicDay;
    UILabel *rightLab;
    
    BMKLocationService *_locService;
    BMKGeoCodeSearch *_searcher;
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption;
    //城市
    UIButton *btnCity;
    BOOL isPostOk;//判断是否请求了网络了
    
    //顶部图片
    NSArray *homePhotos;
    
    //通知
    NSDictionary *dicNotice;
    
    //政府招商
    NSArray *goveproject;
    
    //优质项目
    NSArray *youproject;
    
    //精选资金
    //    NSArray *funds;
    
    //推荐频道
    NSArray *service;
    
    //今日新增
    NSArray *likemany;
    
    //广告页
    LSWebPages * lsWebPages;
    NSString * url_out;
    
    //个人资料
    NSDictionary * userDataDict;
    
    BAddressPickerController *addressPickerController;
    
    NSInteger page;
    
    NSString * or_Number;
    BOOL  isSetPayPass;
    NSString * projectId;
    double price;
}
@property (strong, nonatomic)hotIndustryView * hotIndustryView;
@property (strong, nonatomic) LSPromptAlertVC * LSPromptAlert;
@property (weak, nonatomic) IBOutlet UIButton *topPromptBtn;


@property (nonatomic, strong) UIWindow *overlayWindow;
//说有白线，加一条蓝色线遮盖掉
@property (nonatomic, strong) UIView *blueLineView;
@end

@implementation HomePage
@synthesize overlayWindow;
#pragma mark - 初始化

#pragma mark - 完善个人资料
- (IBAction)topPromptBtn:(UIButton *)sender {
    
    detailProfile * detail = [[detailProfile alloc]init];
    detail.dataDict = [NSMutableDictionary dictionaryWithDictionary:userDataDict];
    [self.navigationController pushViewController:detail animated:YES];
}

-(UIWindow *)overlayWindow{
    
    if(!overlayWindow) {
        overlayWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        overlayWindow.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        overlayWindow.backgroundColor = [UIColor clearColor];
        overlayWindow.userInteractionEnabled = YES;
        overlayWindow.windowLevel = UIWindowLevelStatusBar;
    }
    return overlayWindow;
    
}

-(LSPromptAlertVC *)LSPromptAlert{
    
    if (!_LSPromptAlert) {
        _LSPromptAlert = [[LSPromptAlertVC alloc]init];
    }
    return _LSPromptAlert;
    
}

-(hotIndustryView *)hotIndustryView{
    if (!_hotIndustryView) {
        _hotIndustryView = [[[NSBundle mainBundle]loadNibNamed:@"hotIndustryView" owner:self options:nil]lastObject];
    }
    return _hotIndustryView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        
        NSArray *list=self.navigationController.navigationBar.subviews;
        
        for (id obj in list) {
            
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView=(UIImageView *)obj;
                
                NSArray *list2=imageView.subviews;
                
                for (id obj2 in list2) {
                    
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        
                        UIImageView *imageView2=(UIImageView *)obj2;
                        
                        imageView2.hidden=YES;
                        
                    }
                    
                }
                
            }
            
        }
        
    }

    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15.f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    if ([USER_DEFAULTS objectForKey:@"token"]==nil) {
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 40.0f)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = [UIImage imageNamed:@"logo1"];
    self.navigationItem.titleView = imageView;
    
    isPostOk = NO;
    //初始化检索对象
    _searcher =[[BMKGeoCodeSearch alloc]init];
    _searcher.delegate = self;
    
    reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    [self startPostNetWork];
    
    if (allConstMemberid) {
        [self startPostNetWorkWithUserData];
    }
    //说有白线，加一条蓝色线遮盖掉
    if (!self.blueLineView) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, screenW, 1)];
        lineView.backgroundColor = RGB(74, 141, 237);
        self.blueLineView = lineView;
    }
    [self.navigationController.navigationBar addSubview:self.blueLineView];
}

#pragma mark - 首页广告

-(void)jumpWebView{
    
    NSLog(@"%s",__func__);
    
    [self closeLsWebPages];

    LSPageWebVC * LSPageWeb = [[LSPageWebVC alloc]init];
    LSPageWeb.url_out = url_out;
    [self presentViewController:LSPageWeb animated:YES completion:nil];
}

-(void)closeLsWebPages{
    //淡出动画，再关闭视图
    [UIView animateWithDuration:1.0f animations:^{
        lsWebPages.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [overlayWindow removeFromSuperview];
        overlayWindow = nil;
    }];

}

-(void)startTime{
    __block int timeout = 5; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self closeLsWebPages];
//                [lsWebPages.closeBtn setTitle:@"跳过广告" forState:0];
            });
        }else{
            int seconds = timeout % 5;
            NSString *strTime = [NSString stringWithFormat:@"%d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                
                [lsWebPages.closeBtn setTitle:[NSString stringWithFormat:@"跳过%@s",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];

            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 只执行一次,广告图
    static dispatch_once_t justDoOnce;
    dispatch_once(&justDoOnce, ^{
    
        lsWebPages = [LSWebPages LSWebPagesInit];
        lsWebPages.closeBtn.layer.masksToBounds = YES;
        lsWebPages.closeBtn.layer.cornerRadius = 5.0f;

        [self.overlayWindow addSubview:lsWebPages];
        [self.overlayWindow setHidden:NO];
        
        [lsWebPages.closeBtn addTarget:self action:@selector(closeLsWebPages) forControlEvents:UIControlEventTouchUpInside];
        
        [LSHttpTool sendHttpData:@"getAdver_app_user.im" params:nil success:^(id responseObject) {
            
            if (responseObject[@"data"][@"homePhotos"][0][@"urlPhoto"]) {
                
                [self startTime];
                
                [lsWebPages.backGroundImg sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"homePhotos"][0][@"urlPhoto"]]];
                url_out = responseObject[@"data"][@"homePhotos"][0][@"url_out"];
                
                [lsWebPages.backBtnImg addTarget:self action:@selector(jumpWebView) forControlEvents:UIControlEventTouchUpInside];
                
                
            }
            
            
        } failure:^(NSError *error) {
            
            NSLog(@"状态错误:%@",error);
            
        }];
        
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentSuccessView:)name:@"tableView_loveNotBlance" object:nil];
   
    self.view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];

    homePhotos = [NSArray array];
    
    // 声明这张图片用原图(别渲染)
    UIImage *selectedImgitemHome = [UIImage imageNamed:@"btn_sy_click"];
    selectedImgitemHome = [selectedImgitemHome imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navigationController.tabBarItem setSelectedImage:selectedImgitemHome];
    
    //w:120
    UIView *leftView = [[UIView alloc] initWithFrame:(CGRect){0,0,110,44}];
    //    leftView.backgroundColor = [UIColor redColor];
    
    //城市
    btnCity = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [btnCity setTitle:@"重庆市" forState:UIControlStateNormal];
    [btnCity setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnCity addTarget:self action:@selector(btnClickSelectedCity) forControlEvents:UIControlEventTouchUpInside];
    //    [btnCity setBackgroundColor:[UIColor redColor]];
    
    //按钮内容左对齐
    btnCity.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnCity.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    btnCity.frame = (CGRect){0,2,80,40};
    [btnCity setImage:[UIImage imageNamed:@"icon_dizhi"] forState:UIControlStateNormal];
    
    [btnCity setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
    
    [leftView addSubview:btnCity];
    
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    //右item
    
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTarget:self action:@selector(fabuChangeSend) image:@"Compose" highImage:@"Compose"];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    // 设置尾部
    //    _mainTableView.mj_footer = footer;
    
    
    
    loopScrollViewMain = [[XTLoopScrollView alloc] init];
    loopScrollViewMain.delegate = self;
    
    loopScrollView1 = [[XTLoopScrollView alloc] initWithFrame:(CGRect){8,0,screenW,173}];
    loopScrollView1.delegate = self;
    
    
    loopScrollView2 = [[XTLoopScrollView alloc] initWithFrame:(CGRect){8,0,screenW,173}];
    loopScrollView2.delegate = self;
    
    
    _tableV_Love = [[TableViewC_CaiNiXiHuan alloc] init];
    _tableV_Love.homeVC = self;
    
    _tableV_tui = [[TableViewC_TuiJianPinDao alloc] init];
    _tableV_tui.homeVC = self;
    _tableV_tui.index = 1;
    
    self.hotIndustryView.frame = CGRectMake(0, 37, screenW, 196);
    
    // 监听行业按钮
    self.hotIndustryView.guiDaoBtn.tag = 0;
    [self.hotIndustryView.guiDaoBtn addTarget:self action:@selector(goXiangMu:) forControlEvents:UIControlEventTouchUpInside];
    
    self.hotIndustryView.shengWuBtn.tag = 1;
    [self.hotIndustryView.shengWuBtn addTarget:self action:@selector(goXiangMu:) forControlEvents:UIControlEventTouchUpInside];
    
    self.hotIndustryView.gaoDuanBtn.tag = 2;
    [self.hotIndustryView.gaoDuanBtn addTarget:self action:@selector(goXiangMu:) forControlEvents:UIControlEventTouchUpInside];
    
    self.hotIndustryView.jinRongBtn.tag = 3;
    [self.hotIndustryView.jinRongBtn addTarget:self action:@selector(goXiangMu:) forControlEvents:UIControlEventTouchUpInside];
    
    self.hotIndustryView.huoYunBtn.tag = 4;
    [self.hotIndustryView.huoYunBtn addTarget:self action:@selector(goXiangMu:) forControlEvents:UIControlEventTouchUpInside];
    
    page = 1;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewVC) name:@"TuiSong" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewBage) name:@"TuiSongBage" object:nil];
    
    
    
        dispatch_async(dispatch_get_main_queue(), ^{
            
    int count = [[RCIMClient sharedRCIMClient]getTotalUnreadCount];
    
    if (count != 0 && count != -1) {
        
        [self.tabBarController.tabBar showBadgeOnItemIndex:1];
        
    }
        });
    
    
    
    //监听按钮
    [self.LSPromptAlert.PromptAlertView.becomeVIPBtn addTarget:self action:@selector(clickBecomeVIPBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.LSPromptAlert.PromptAlertView.alipayBtn addTarget:self action:@selector(clickAlipayBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.LSPromptAlert.PromptAlertView.balancePayBtn addTarget:self action:@selector(clickCashBtn) forControlEvents:UIControlEventTouchUpInside];
    
    //支付回调通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView) name:@"alipayResult" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentFailedView) name:@"alipayFailed" object:nil];
    
    //将返回数据保存到数据库中
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        
        Person * tmp = [Person MR_findFirstByAttribute:@"userid" withValue:allConstMemberid inContext:localContext];
        
        if (tmp.headPhoto == nil) {
            //图片 - 二进制 - 字符串
            UIImageView * img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
            [img sd_setImageWithURL:[NSURL URLWithString:allConstMemberImgStr]];
            
            NSData * imgData = UIImageJPEGRepresentation(img.image, 1.0f);
            tmp.headPhoto = imgData;
        }
        
        
    }
                      completion:^(BOOL contextDidSave, NSError *error) {
                          NSLog(@"=-===%@", (contextDidSave ? @"保存图片成功" : @"保存图片失败"));
                          
                      }];

    
}

-(void)presentSuccessView:(NSNotification *)notification{

//    NSLog(@"%@",notification);
    
        [LSHttpTool sendHttpData:@"buyProjectDetail_app_pay.im.lensum" params:notification.userInfo success:^(id responseObject) {


            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                
                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                dict[@"projectId"] = notification.userInfo[@"resId"];
                dict[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
                
                [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                        
                        [self hideBubble];
                        SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                        SeaVC.dataDict = responseObject[@"data"];
                        SeaVC.projectData = [NSMutableArray arrayWithArray:responseObject[@"data"][@"commentsList"]];
                        
                        [self.navigationController pushViewController:SeaVC animated:YES];
                        
                    }else{

                        [self showSingleIconBubble:[responseObject objectForKey:@"msg"]];
                        
                    }
                    
                } failure:^(NSError *error) {

                   [self showSingleIconBubble:@"网络连接错误"];
                    
                }];
                
            }else{

                [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                
            }

        } failure:^(NSError *error) {

            // 跳转至支付成功页面
            LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
            [LSPayResult setCashTypeWithCashFailed];

            [self hideBubble];
        }];

}

-(void)presentViewVC{

    self.tabBarController.selectedIndex = 2;

}

-(void)presentViewBage{

    [self.tabBarController.tabBar showBadgeOnItemIndex:1];
}




#pragma mark - 右边发布按钮
- (void)fabuChangeSend{
    
    if (!allConstMemberid) {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        alert.tag = 10;
        [alert show];
        
    }else{
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
        mainFabu *fabu = [storyboard instantiateViewControllerWithIdentifier:@"mainFabu"];
        [self.navigationController pushViewController:fabu animated:YES];
        
    }

}


-(void)goXiangMu:(UIButton *)btn{
    NSString *str;
    
    switch (btn.tag) {
        case 0:
            str = @"市政基建";
            break;
            
        case 1:
            str = @"生态环保";
            break;
            
        case 2:
            str = @"交通运输";
            break;
            
        case 3:
            str = @"生物医药";
            break;
            
        case 4:
            str = @"社会保障";
            break;
            
        default:
            break;
    }
    
    UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    
    SearchProject * searchVC = [sb instantiateViewControllerWithIdentifier:@"SearchProject"];
    
    searchVC.searchStr = str;
    
    [self.navigationController pushViewController:searchVC animated:YES];
    
}

- (void)loadMoreData
{
    
}
#pragma mark - 热门行业更多按钮
- (IBAction)moreBtn:(UIButton *)sender {
    industryClassificationVC * industryVC = [[industryClassificationVC alloc]init];
    industryVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:industryVC animated:YES];
    
}
#pragma mark - 今日新增更多按钮
- (IBAction)newMoreBtn:(UIButton *)sender {
    
    [self performSegueWithIdentifier:@"searchProject" sender:self];
}
#pragma mark - 推荐频道换一批
- (IBAction)changeBtn:(UIButton *)sender {
    
    _tableV_tui.index ++;
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    page ++;
    dic[@"page"] = @(page);
    dic[@"userId"] = allConstMemberid;
    
    [LSHttpTool sendHttpData:@"homeTuijianGove_app_user.im" params:dic success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        service = dicInfo[@"data"][@"tuijianGove"];
        
        [_mainTableView reloadData];
        
    } failure:^(NSError *error) {
 
        [self showSingleIconBubble:@"网络连接错误"];
        
    }];
}


#pragma mark - 选择城市
- (void)btnClickSelectedCity
{
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    addressPickerController = [[BAddressPickerController alloc] initWithFrame:self.view.frame];
    addressPickerController.dataSource = self;
    addressPickerController.delegate = self;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    //self.navigationItem.leftBarButtonItem = leftItem;
    
    addressPickerController.navigationItem.leftBarButtonItem = leftItem;
    //    [self addChildViewController:addressPickerController];
    //    [self.view addSubview:addressPickerController.view];
    
    [self.navigationController pushViewController:addressPickerController animated:YES];
}
- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
//实现BAddressPickerDataSource数据源协议
-(NSArray*)arrayOfHotCitiesInAddressPicker:(BAddressPickerController *)addressPicker
{
    
    return @[@"北京",@"上海",@"深圳",@"杭州",@"广州",@"武汉",@"天津",@"重庆",@"成都",@"苏州"];
    
}

//实现BAddressPickerDelegate代理协议
-(void)addressPicker:(BAddressPickerController *)addressPicker didSelectedCity:(NSString *)city
{
    [btnCity setTitle:city forState:UIControlStateNormal];
    [addressPickerController.navigationController popViewControllerAnimated:YES];
    //    NSLog(@"%@",city);
    [USER_DEFAULTS setObject:city forKey:@"district"];//区
    [USER_DEFAULTS synchronize];
    
        [self startPostNetWork];
}

- (void)beginSearch:(UISearchBar *)searchBar{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)endSearch:(UISearchBar *)searchBar{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0://滑动图片
            //            return 229;
            
            return 180;
            break;
        case 1://9个按钮
            return 180;
            break;
        case 2://热门行业
            return 233;
            break;

        case 3://推荐频道
            return 31+75*service.count;
            break;
        case 4://今日新增42+110
            return 37+102*likemany.count;
            break;
            
        default:
            return 44;
            break;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *iCarousel_Identifier = @"iCarousel";//首页
    static NSString *cellZFZS = @"cellZFZS";//政府招商、优质项目
    static NSString *cellJXZJ = @"cellJXZJ";//热门行业
    static NSString *cellHotFuWu = @"cellHotFuWu";//推荐频道
    static NSString *cellLove = @"cellLove";//今日新增
    
    UITableViewCell *cell;
    
    
    switch (indexPath.row) {
        case 0://政府招商
        {
            cell = [tableView dequeueReusableCellWithIdentifier:cellZFZS forIndexPath:indexPath];
            loopScrollView1 = (XTLoopScrollView *)[cell viewWithTag:12];
            
            
        }
            break;
        case 1://9个按钮
        {
            
            PageButtonsCell *btnCell = [[PageButtonsCell alloc] init];
            for (UIButton *button in btnCell.muBtnAry) {
                [button addTarget:self action:@selector(btnClickEight:) forControlEvents:UIControlEventTouchUpInside];
            }
            return btnCell;
        }
            break;
        case 2://热门行业
        {
            cell = [tableView dequeueReusableCellWithIdentifier:cellJXZJ forIndexPath:indexPath];
            
            [cell addSubview:self.hotIndustryView];
            
        }
            break;
        case 3://推荐频道
        {
            //如果为空没做处理
            
            if (!cell) {
                cell = [tableView dequeueReusableCellWithIdentifier:cellHotFuWu forIndexPath:indexPath];
                cell.width = screenW;
                _tableV_tui.tableView = (UITableView *)[cell viewWithTag:10];
                
//                _tableV_tui.tableView.translatesAutoresizingMaskIntoConstraints = YES;
//                CGRect rect1 = _tableV_tui.tableView.frame;
//                rect1.size.height = 75*service.count;
//                rect1.origin.y = 31;
//                _tableV_tui.tableView.frame = rect1;
//                _tableV_tui.tableView.width = screenW;
                [_tableV_tui setDelegte];

                _tableV_tui.aryInfo = service;
                [_tableV_tui.tableView reloadData];
             
            }
            
        }
            break;
        case 4://今日新增
        {
            cell = [tableView dequeueReusableCellWithIdentifier:cellLove forIndexPath:indexPath];
            
            _tableV_Love.tableView = (UITableView *)[cell viewWithTag:10];
//            _tableV_Love.tableView.translatesAutoresizingMaskIntoConstraints = YES;
//            CGRect rect1 = _tableV_Love.tableView.frame;
//            rect1.size.height = 100*likemany.count;
//            _tableV_Love.tableView.frame = rect1;
//            _tableV_Love.tableView.width = screenW;
            [_tableV_Love setDelegte];
            
            _tableV_Love.aryInfo = likemany;
            [_tableV_Love.tableView reloadData];
            //            }
        }
            
            break;
            
        default:
            break;
    }
    
    
    
    return cell;
    
}


-(void)guanZhu{
    [_tableV_tui.tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态

}


//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    if (!isPostOk) {
        //发起反向地理编码检索
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
        
        reverseGeoCodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
        
        if(flag)
        {
            isPostOk = YES;
            if (allConstMemberToken !=nil) {
                
                [SVProgressHUD showWithStatus:@"定位中..."];
            }
            
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    }
    
    [SVProgressHUD dismiss];
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    //    NSLog(@"%@",error);
    
    if (allConstMemberToken !=nil) {
        if (!isPostOk) {
            isPostOk = YES;
            //            [self startPostNetWork];
        }
    }
    
    
}


//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        //      NSLog(@"%@",result.address);
//        [btnCity setTitle:result.addressDetail.city forState:UIControlStateNormal];
        [USER_DEFAULTS setObject:result.addressDetail.province forKey:@"province"];//省
        [USER_DEFAULTS setObject:result.addressDetail.city forKey:@"city"];//市
        [USER_DEFAULTS setObject:result.addressDetail.district forKey:@"district"];//区
        [USER_DEFAULTS setObject:result.addressDetail.streetName forKey:@"streetName"];//街道
        [USER_DEFAULTS setObject:result.addressDetail.streetNumber forKey:@"streetNumber"];//街道号码
        [USER_DEFAULTS synchronize];
        
//        if ([USER_DEFAULTS objectForKey:@"token"] ==nil) {
//                      [self startPostNetWork];
//        }
        
        
    }
    else {
        isPostOk = NO;
        //NSLog(@"抱歉，未找到结果");
    }
}

//不使用时将delegate设置为 nil
-(void)viewWillDisappear:(BOOL)animated
{
    _searcher.delegate = nil;
    //    self.tableV_tui = nil;
    //视图将要结束时，去掉加的这条蓝线
    [self.blueLineView removeFromSuperview];
}

- (void)startPostNetWork
{
    NSString *strAddress = @"";
    
    
    NSMutableString *strDistrict = [NSMutableString stringWithFormat:@"%@",[USER_DEFAULTS objectForKey:@"district"]];
    if ([strDistrict isEqualToString:@"(null)"]) {
        strDistrict = @"";
    }
    NSRange range = [strDistrict rangeOfString:@"区"];//判断字符串是否包含
    //if (range.location ==NSNotFound)//不包含
    if (range.length >0)//包含
    {
        strAddress = [USER_DEFAULTS objectForKey:@"city"];
    }
    else//不包含
    {
        [strDistrict stringByReplacingOccurrencesOfString:@"县" withString:@""];
        strAddress = strDistrict;
    }
    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    //    [muDicParameters setObject:strAddress forKey:@"address"];//城市
    muDicParameters[@"userId"] = allConstMemberid;
    //    [muDicParameters setObject:@"重庆市" forKey:@"address"];//城市
    muDicParameters[@"address"] = strAddress;
    
    if (![strAddress isEqualToString:@""]) {
        [btnCity setTitle:strAddress forState:UIControlStateNormal];
    }
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getHome_data_app_user.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        //        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

            NSDictionary *dicData = [dicInfo objectForKey:@"data"][0];
            
            //顶部图片
            homePhotos = dicData[@"homePhotos"];
            NSMutableArray *muaAryPhotos = [NSMutableArray array];
            for (int i =0; i<homePhotos.count; i++) {
                [muaAryPhotos addObject:homePhotos[i][@"urlPhoto"]];
                
            }
            
            [loopScrollViewMain startWithFrame:loopScrollViewMain.frame andImageList:muaAryPhotos canLoop:YES duration:5.0 isOKYuandian:YES];
            loopScrollViewMain.color_pageControl = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:0.6f];
            loopScrollViewMain.color_currentPageControl = [UIColor colorWithRed:32.0f/255.0f green:165.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
            //            loopScrollViewMain.delegate = self;
            //service热门服务=1ary、likemany猜你喜欢=5ary、youproject优质项目=2ary、funds精选资金=1ary
            //通知
            dicNotice = dicData[@"notice"];
            
            //政府招商
            
            goveproject = dicData[@"goveproject"];
            if (goveproject.count > 0) {
                
                NSMutableArray *muaAryPhotosGove = [NSMutableArray array];
                for (int i =0; i<goveproject.count; i++) {
                    [muaAryPhotosGove addObject:goveproject[i][@"photos"][0]];
                    
                }
                loopScrollView1.aryInfoData = goveproject;
                [loopScrollView1 startWithFrame:loopScrollView1.frame andImageList:muaAryPhotosGove canLoop:YES duration:5.0 isOKYuandian:NO];
                loopScrollView1.delegate = self;
            }
            

            
            //精选资金
            //            funds = dicData[@"funds"];
            
            
            //优质项目
            youproject = dicData[@"youproject"];
            
            
            //推荐频道
            service = dicData[@"tuijianGove"];
            
            //今日新增
            likemany = dicData[@"newsProject"];
            
            [_mainTableView reloadData];
            
            
        }else {

        }
        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self showSingleIconBubble:error.localizedDescription];

    }];
}

#pragma mark - 10个按钮事件
- (void)btnClickEight:(UIButton *)btn
{
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    switch (btn.tag) {
        case 30://找项目
        {
            [self performSegueWithIdentifier:@"searchProject" sender:self];
        }
            break;
        case 31: //供应链
        {
            TrickTender *trickVC = [[TrickTender alloc] init];
            trickVC.supplyChainStr = @"供应链";
            [self.navigationController pushViewController:trickVC animated:YES];
        }
            break;
        case 32://找人脉
        {
            searchContactsVC * searchContacts = [[searchContactsVC alloc]init];
            [self.navigationController pushViewController:searchContacts animated:YES];
            //            [self performSegueWithIdentifier:@"searchcontacts" sender:self];
        }
            break;
        case 33://PPP
        {
            if (!allConstMemberid) {
                
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
                [alert show];
                
            }else{
                
                [self performSegueWithIdentifier:@"toPPP" sender:self];
                
            }
        }
            break;
            //BusinessActivity
        case 34://找活动
        {
            [self performSegueWithIdentifier:@"BusinessActivity" sender:self];
            //            TrickTender *trickVC = [[TrickTender alloc] init];
            //            [self.navigationController pushViewController:trickVC animated:YES];
        }
            break;
        case 35://找资金
        {
            [self performSegueWithIdentifier:@"searchPrice" sender:self];
        }
            break;
        case 36://企业服务
        {
            [self performSegueWithIdentifier:@"BusinessService" sender:self];
        }
            break;
        case 37://政商参考
        {
            [self performSegueWithIdentifier:@"Consult" sender:self];
        }
            break;
        case 38://招聘求职
        {
            [self performSegueWithIdentifier:@"Recruitment" sender:self];
        }
            break;
            
        case 39://招投标
        {

            TrickTender *trickVC = [[TrickTender alloc] init];
            [self.navigationController pushViewController:trickVC animated:YES];

//            if (!allConstMemberid) {
//                
//                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
//                alert.tag = 10;
//                [alert show];
//                
//            }else{
//                
//                 [self performSegueWithIdentifier:@"toPPP" sender:self];
//                
//            }
      
            //            if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
            //            }else {
            //
            //                //登录
            //                UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            //                UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
            //                [self presentViewController:loginNAV animated:YES completion:nil];

            
        }
            break;

            
            
        default:
            break;
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (allConstMemberid) {
        if (buttonIndex == 1) {
            [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
            
            UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
            //充值
            LSRechargeVC * LSRecharge = [[LSRechargeVC alloc]init];
            
            switch (alertView.tag) {
                case 10:
                    
                    [self presentViewController:loginNAV animated:YES completion:nil];
                    
                    break;
                    
                case 20:
                    
                    [self.navigationController pushViewController:LSRecharge animated:YES];
                    
                    break;
                    
                case 30:
                {
                    
                    UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    ForgetPassWord *ForgetPassWord = [LoginAndRegister instantiateViewControllerWithIdentifier:@"forgetpassword"];
                    ForgetPassWord.titleStr = @"修改支付密码";
                    [self.navigationController pushViewController:ForgetPassWord animated:YES];
                    
                }
                    break;
                    
                default:
                    break;
            }
        }

    }else{
        if (buttonIndex == 1) {
            //登录
            UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
            [self presentViewController:loginNAV animated:YES completion:nil];
        }
    }
    
}


#pragma mark - XTLoopScrollViewDelegate
- (void)tapingCurrentIndex:(NSInteger)currentIndex andWho:(XTLoopScrollView *)XTLoopScroll
{
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    //    UIStoryboard *Storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    //    Project_Detail *project_detail = [Storyboard instantiateViewControllerWithIdentifier:@"project_detail"];
    SearchProjectInfoVC * searchVC = [[SearchProjectInfoVC alloc]init];
    if (XTLoopScroll == loopScrollViewMain) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:homePhotos[currentIndex][@"url_out"]]];
        //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    }else if (XTLoopScroll == loopScrollView1) {
        //NSLog(@"政府招商:%ld",(long)currentIndex);
        //goveproject
//        searchVC.projectId = goveproject[currentIndex][@"projectId"];
//        [self.navigationController pushViewController:searchVC animated:YES];
        if (allConstMemberid) {
            [self showRoundProgressWithTitle:@"请稍后..."];
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            dict[@"projectId"] = goveproject[currentIndex][@"projectId"];
            dict[@"userId"] = allConstMemberid;
            
            [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                
                if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                    
                    [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
                    
                    SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                    SeaVC.dataDict = dicInfo[@"data"];
                    SeaVC.projectData = [NSMutableArray arrayWithArray:dicInfo[@"data"][@"commentsList"]];
                    
                    [self.navigationController pushViewController:SeaVC animated:YES];
                    
                }else if ([[dicInfo objectForKey:@"result"] integerValue] == 2){

                    [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                    
                }else if ([[dicInfo objectForKey:@"result"]integerValue] == 3){
                    
                    isSetPayPass = [dicInfo[@"data"][@"isSetPayPass"] boolValue];
                    price = [dicInfo[@"data"][@"powerMoney"]floatValue];
                    
                    projectId = goveproject[currentIndex][@"projectId"];
                    self.LSPromptAlert.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                    [self presentViewController:self.LSPromptAlert animated:YES completion:nil];
                    
                }
                

            } failure:^(NSError *error) {

                [self showSingleIconBubble:@"网络连接错误"];
                
            }];
            
        }else{
            
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            
            alert.tag = 10;
            
            [alert show];
            
        }
        
    }else {
        //NSLog(@"优质项目:%ld",(long)currentIndex);
        //youproject
        //        project_detail.projectId = youproject[currentIndex][@"projectId"];
        //        [self.navigationController pushViewController:project_detail animated:YES];
    }
}

#pragma mark - 通知跳转
- (void)btnClickNotice
{
    //    dicNotice
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com"]];
}

#pragma mark - 精选资金

#pragma mark - 热门服务




#pragma mark - 弹框按钮监听
//跳转会员界面
-(void)clickBecomeVIPBtn{
    
    [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
    
    LSBecomeVIPVC * LSBecomeVIP = [[LSBecomeVIPVC alloc]init];
    [self.navigationController pushViewController:LSBecomeVIP animated:YES];
    
}

#pragma mark - 支付回调通知
-(void)clickAlipayBtn{
    
    or_Number = [LSAlipay alipay:@"乐商网" body:@"项目详情" price:0.01f];
    
}

-(void)presentFailedView{
    
    // 跳转至支付失败页面
    LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
    [LSPayResult setCashTypeWithCashFailed];
    [self.navigationController pushViewController:LSPayResult animated:YES];
    
}

-(void)presentView{
    
    [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"token"] = allConstMemberToken;
    dic[@"payUserId"] = allConstMemberid;
    dic[@"payWay"] = @"2";
    dic[@"payMoney"] = @(price);
    dic[@"resId"] = projectId;
    dic[@"order_no"] = or_Number;
    
    [LSHttpTool sendHttpData:@"buyProjectDetail_app_pay.im.lensum" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            dict[@"projectId"] = dic[@"resId"];
            dict[@"userId"] = allConstMemberid;
            
            [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                    
                    [self hideBubble];
                    SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                    SeaVC.dataDict = responseObject[@"data"];
                    SeaVC.projectData = [NSMutableArray arrayWithArray:responseObject[@"data"][@"commentsList"]];
                    
                    [self.navigationController pushViewController:SeaVC animated:YES];
                    
                }else{

                    [self showSingleIconBubble:[responseObject objectForKey:@"msg"]];
                    
                }
                
            } failure:^(NSError *error) {

                [self showSingleIconBubble:@"网络连接错误"];
                
            }];
            
        }else{

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            
        }
        
    } failure:^(NSError *error) {
        
        // 跳转至支付成功页面
        LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
        [LSPayResult setCashTypeWithExchangeFailed];
        
        [self hideBubble];
    }];
    
}

#pragma mark - 余额支付
-(void)clickCashBtn{
    
    NSString * balanceStr = [self.LSPromptAlert.PromptAlertView.balanceLabel.text stringByReplacingOccurrencesOfString:@"￥"withString:@""];
    
    double balance = [balanceStr floatValue];
    
    if (balance < 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                        message:@"余额不足！"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"立刻充值",nil];
        alert.delegate = self;
        alert.tag = 20;
        [alert show];
        
    }else{
        
        if (isSetPayPass) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                            message:@"未设置支付密码"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"立即设置",nil];
            alert.delegate = self;
            alert.tag = 30;
            [alert show];
            
        }else{
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"余额支付" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            
            UITextField *title = [alert textFieldAtIndex:0];
            [title setSecureTextEntry:YES];
            title.borderStyle = UITextBorderStyleNone;
            title.textColor = [UIColor redColor];
            title.textAlignment = NSTextAlignmentCenter;
            title.font = [UIFont systemFontOfSize:16.0f];
            title.placeholder = @"请输入支付密码";
            
            
            [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
                if(buttonIndex == 1){
                    UITextField *tf=[alert textFieldAtIndex:0];
                    if (tf.text.length > 0) {
                        
                        [self showRoundProgressWithTitle:@"请稍后..."];
                        
                        NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
                        dic[@"token"] = allConstMemberToken;
                        dic[@"payUserId"] = allConstMemberid;
                        dic[@"payWay"] = @"1";
                        dic[@"payMoney"] = @(price);
                        dic[@"resId"] = projectId;
                        dic[@"payPass"] = tf.text;
                        
                        [LSHttpTool sendHttpData:@"buyProjectDetail_app_pay.im.lensum" params:dic success:^(id responseObject) {
                            
                            [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
                            
                            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                
                                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                                dict[@"projectId"] = dic[@"resId"];
                                dict[@"userId"] = allConstMemberid;
                                
                                [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                        
                                        [self hideBubble];
                                        SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                                        SeaVC.dataDict = responseObject[@"data"];
                                        SeaVC.projectData = [NSMutableArray arrayWithArray:responseObject[@"data"][@"commentsList"]];
                                        
                                        [self.navigationController pushViewController:SeaVC animated:YES];
                                        
                                    }else{

                                        [self showSingleIconBubble:[responseObject objectForKey:@"msg"]];
                                        
                                    }
                                    
                                } failure:^(NSError *error) {

                                    [self showSingleIconBubble:@"网络连接错误"];
                                    
                                }];
                                
                            }else{

                                [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                                
                            }
                            
                            
                        } failure:^(NSError *error) {
                            
                            // 跳转至支付成功页面
                            LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
                            [LSPayResult setCashTypeWithCashFailed];
                            [self hideBubble];
                        }];
                        
                    }else{
                        
                        NSString *strMsg = @"密码不能为空";
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:strMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                        [alert show];
                        
                    }
                }
            }];
            
            
        }
        
    }
    
}

- (void)startPostNetWorkWithUserData
{
    
    //token=rE3F2m8AvfC7CVh85O9q&userId=9&userType=用户类型 1-个人，2-企业，3-政府
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"userType"];//用户类型 1-个人，2-企业，3-政府
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"MyBasicMessage_app_myHome.im.lensum"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//                NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            userDataDict = dicInfo[@"data"];

            if ([allConstMemberUserType integerValue] == 1) {//个人
                
                if (![dicInfo[@"data"][@"userName"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyName"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"positionName"] isEqualToString:@"null"]&& ![dicInfo[@"data"][@"address"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"goodatfield"] isEqualToString:@"null"]&& ![dicInfo[@"data"][@"myneeds"] isEqualToString:@"null"]) {
                    
                    self.topPromptBtn.hidden = YES;
                    
                }else{
                
                    self.topPromptBtn.hidden = NO;
                
                }
                
            }else if ([allConstMemberUserType integerValue] == 2) {//企业
                
                if (![dicInfo[@"data"][@"userName"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyNature"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyIndustry"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyScale"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"address"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyField"] isEqualToString:@"null"] && ![dicInfo[@"data"][@"companyBusNeeds"] isEqualToString:@"null"]) {
                    
                    self.topPromptBtn.hidden = YES;
                    
                    
                }else{
                
                    self.topPromptBtn.hidden = NO;
                
                }
                
            }
            
        }else {

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self showSingleIconBubble:error.localizedDescription];
        
    }];
}

@end
